package ru.diamond.home;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Client {
	Socket client;
	String name;
	int serverport;
	ObjectOutputStream oos; 
	ObjectInputStream ois;
	
	private SimpleDateFormat sdf = new SimpleDateFormat("YYYY.MM.dd HH:mm:ss");
	
	public Client(String name, int serverPort) throws UnknownHostException, IOException
	{
		this.name = name;
		this.serverport = serverPort;
		client = new Socket("localhost", serverPort);
		oos = new ObjectOutputStream (client.getOutputStream());
		ois = new ObjectInputStream(client.getInputStream());
	}
	
	@Override
	public void finalize() 
	{
		close();
		try {
			super.finalize();
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void send(String data) throws Exception
	{
		Message mess = new Message(data, name);
		oos.writeObject(mess);
		oos.flush();
		
		mess  = (Message) ois.readObject();
		System.out.println(sdf.format(new Date()) + "\t " + name + ":\t server answer = " + mess.message);
	}
	
	public void close()
	{
		try {
			client.close();
			ois.close();
			oos.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
